<?php

namespace App\Service;

use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;

/**
 * JWT 业务类
 *
 * @author WangBin
 */
class JWTService extends Singleton
{
    /**
     * 生成 token
     *
     * @param $data
     * @return string
     */
    public function encode($data)
    {
        $key = config('jwt.key', '=-3j5EzrearZplMgoHZedZI6J83D7Fm8vtxLRVzrypeI4=');
        $issue = config('jwt.issue', 'hiyee.im');
        $expire = config('jwt.expire', 10 * 60 * 60);
        $payload = [
            'issue' => $issue,
            'expired_at' => time() + $expire,
            'data' => $data
        ];
        return JWT::encode($payload, $key, 'HS256');
    }

    /**
     * 解析 token
     *
     * @param $token
     * @return array|false
     */
    public function decode($token)
    {
        $key = config('jwt.key', '=-3j5EzrearZplMgoHZedZI6J83D7Fm8vtxLRVzrypeI4=');
        try {
            JWT::$leeway = 20;//当前时间减去20，把时间留点余地
            $decoded = JWT::decode($token, $key, ['HS256']); //HS256是默认方式，`在这里插入代码片`这里要和签发的时候对应
            $arr = (array)$decoded;
            return (array)$arr['data'];
        } catch (SignatureInvalidException $e) {  //签名不正确
            return false;
        } catch (BeforeValidException $e) {  // 签名在某个时间点之后才能用
            return false;
        } catch (ExpiredException $e) {  // token过期
            return false;
        }
    }
}